import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, 
  baseURL: 'http://10.10.3.212:1221/material/', //阿里云
  timeout: 30000, // request timeout
  // headers: {
  //   "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
  // },
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['X-Material-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// // response interceptor
service.interceptors.response.use(
  response => {
    const res = response
    if (res.data.code === 501) {
      store.dispatch("user/logout");
      Message({
        message: res.data.msg,
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      return res
    }

  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
